import { useNavigation, useSubmit, useActionData } from "react-router";
import { Card, Form, Input, Button } from "antd";
/**
 * 一般用于表单提交，删除，修改等操作。
 * 只有POST DELETE PATCH PUT等请求才会触发action，所以适合用来提交表单
 * useSubmit 是一个 React-router 的钩子函数，用于提交表单。
 *
 * useActionData 是一个 React-router 的钩子函数，用于获取路由的 action 数据。
 * @returns
 */
export default function RouteForm() {
  const { state } = useNavigation();
  console.log(state);

  const actionData = useActionData();
  console.log("actionData", actionData);

  const submit = useSubmit();

  const formData = new FormData();
  formData.append("username", "test@test.com");
  formData.append("password", "123456");
  const submitData = async () => {
    submit(formData, { method: "post" });
    // 提交json
    // submit(JSON.stringify({ username: "test@test.com", password: "123456" }), {
    //   method: "POST",
    //   encType: "application/json",
    // });

    // // 提交text
    // submit("test", { method: "POST", encType: "text/plain" });/
    // // 提交urlencoded数据
    // submit(
    //   { email: "test@test.com", password: "123456" },
    //   { method: "POST", encType: "application/x-www-form-urlencoded" }
    // );
    // // 提交queryString数据
    // submit(
    //   [
    //     ["email", "test@test.com"],
    //     ["password", "123456"],
    //   ],
    //   { method: "POST" }
    // );
  };
  return (
    <div>
      <h1>RouteForm</h1>
      <p>RouteForm</p>
      <Card title="RouteForm">
        <Form
          onFinish={(values) => {
            console.log(values);
            submit(values, { method: "post" });
          }}
        >
          <Form.Item label="用户名" name="username">
            <Input />
          </Form.Item>
          <Form.Item label="密码" name="password">
            <Input.Password />
          </Form.Item>
          <Form.Item>
            <Button
              type="primary"
              htmlType="submit"
              disabled={state == "loading"}
            >
              提交
            </Button>
          </Form.Item>
        </Form>
      </Card>
      <Button onClick={() => submitData()}>测试</Button>
    </div>
  );
}
